//
//  AddCommodityVC.m
//  yunbaolive
//
//  Created by ybRRR on 2020/2/24.
//  Copyright © 2020 cat. All rights reserved.
//

#import "AddCommodityVC.h"
#import "CommodityTitleView.h"
#import "CommodityDetailView.h"
#import "StandardsView.h"
#import "SelCommodityClassVC.h"
#import <Qiniu/QiniuSDK.h>
#import "CommodityDetailModel.h"
#import "YBStorageObj.h"
@interface AddCommodityVC ()<commodityTitleDelegate,commodityDetailDelegate,UITextFieldDelegate,UIScrollViewDelegate>
{
    UILabel *_classLb; //选择类别
    
    CGFloat titleViewHeight;
    CGFloat detailViewHeight;
    CGFloat standardsHeight;
    CGFloat postageHeight;
    CGFloat commissionHeight;

    UISwitch *postageSwitch;
    
    NSMutableArray* standarsArr;
    
    NSString *one_classidStr;
    NSString *two_classidStr;
    NSString *three_classidStr;
    
    UIView *postageback;
    
    UITextField *postageField;
    UITextField *commissionField;

    NSString *thumbs;// 商品展示图集 英文逗号分隔
    NSString *pictures;//商品内容图集 英文逗号分隔
    
    NSString *videoCorverStr;//视频封面
    NSString *videoHerfStr;//视频链接
    
    BOOL thumbsBool;
    BOOL picturesBool;
    BOOL standardsBool;

    CGFloat currentScrollY;
}
@property (nonatomic, strong)UIScrollView *backScroll;
@property (nonatomic, strong)UIView *commodityClassView;
@property (nonatomic, strong)UIView *bottomView;
@property (nonatomic, strong)CommodityTitleView *titleView;
@property (nonatomic, strong)CommodityDetailView *contentView;
@property (nonatomic, strong)UIView *standardsBackView;
@property (nonatomic, strong)StandardsView *standardsView;
@property (nonatomic, strong)UIView *postageView; //邮费界面
@property (nonatomic, strong)UIView *commissionView;//佣金

@property (nonatomic, strong)UIButton *addStdBtn;

@property (nonatomic, strong)NSArray*titleImgArr;//商品标题图集数组
@property (nonatomic, strong)NSMutableArray *upTitleImgArr;//上传用标题数组

@property (nonatomic, strong)NSArray*detailImgArr;//商品详情图集数组
@property (nonatomic, strong)NSMutableArray *upDetailImgArr;//上传用详情数组

@property (nonatomic, strong)NSMutableArray*standardsImgArr;//商品详情图集数组
@property (nonatomic, strong)CommodityDetailModel *commodityModel;

@end

@implementation AddCommodityVC

#pragma mark----获取商品详情------
-(void)getGoodInfo{
    NSString *url = [purl stringByAppendingFormat:@"?service="];
    NSDictionary *dic = @{
                          @"uid":[Config getOwnID],
                          @"token":[Config getOwnToken],
                          @"goodsid":self.goodsID,
                          };
    [WYNetworking postWithUrl:@"Shop.getGoodsInfo" Dic:dic Suc:^(int code, id info, NSString *msg) {
        if (code ==0) {
            self.commodityModel = [CommodityDetailModel modelWithDictionary:[info firstObject]];
            [self reloadUIData];
        }else{
            [MBProgressHUD showError:msg];
        }

        } Fail:^(id fail) {
            
     }];

}
-(void)initData{
    standarsArr = [NSMutableArray array];
    titleViewHeight = 170;
    detailViewHeight = 330;
    standardsHeight = 330;
    postageHeight = 100;
    commissionHeight = 100;
    currentScrollY = 0;
    self.titleImgArr = [NSArray array];
    self.detailImgArr = [NSArray array];
    self.standardsImgArr = [NSMutableArray array];
    thumbs = @"";
    pictures = @"";
    thumbsBool = NO;
    picturesBool = NO;
    standardsBool = NO;
}
- (UIStatusBarStyle)preferredStatusBarStyle {
    if (@available(iOS 13.0,*)) {
        return UIStatusBarStyleDarkContent;
    }
    return UIStatusBarStyleDefault;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.subNavi.backgroundColor = UIColor.whiteColor;
    self.titleL.textColor = UIColor.blackColor;
    [self.leftBtn setImage:[UIImage imageNamed:@"pub_back_black"] forState:0];
    self.naviLine.hidden = NO;
    self.naviLine.backgroundColor = RGB(245, 245, 245);

    
    if ([self.fromWhere isEqual:@"seller"]) {
        self.titleL.text = YZMsg(@"编辑商品");
        [self getGoodInfo];
    }else{
        self.titleL.text = YZMsg(@"添加商品");
    }
    [self initData];
    _backScroll = [[UIScrollView alloc]init];
    _backScroll.frame= CGRectMake(0, 64+statusbarHeight, _window_width, _window_height-60);
    _backScroll.backgroundColor = RGB(235, 235, 235);
    _backScroll.delegate = self;
    [self.view addSubview:_backScroll];
    UITapGestureRecognizer *hideBoardTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hideKeyBoardClick)];
    [_backScroll addGestureRecognizer:hideBoardTap];
    
    [self.view addSubview:self.bottomView];
    
    [self.backScroll addSubview:self.commodityClassView];
    [self.backScroll addSubview:self.titleView];
    [self.backScroll addSubview:self.contentView];
    [self.backScroll addSubview:self.standardsBackView];
    [self.backScroll addSubview:self.postageView];
    [self.backScroll addSubview:self.commissionView];

    _backScroll.contentSize = CGSizeMake(_window_width, self.titleView.height+self.contentView.height+self.commodityClassView.height+self.standardsBackView.height+self.postageView.height+self.commissionView.height+64+statusbarHeight+60);
    //增加监听，当键盘出现或改变时收出消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow:)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide:)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];

}
-(void)hideKeyBoardClick{
    [self.view endEditing:YES];
}
-(UIView*)bottomView{
    if (!_bottomView) {
        _bottomView = [[UIView alloc]initWithFrame:CGRectMake(0, _window_height-60, _window_width, 60)];
        _bottomView.backgroundColor = UIColor.whiteColor;
        
        UIButton *upBtn = [UIButton buttonWithType:0];
        upBtn.frame= CGRectMake(15, 10, _window_width-30, 40);
        [upBtn setBackgroundColor:Pink_Cor];
        [upBtn setTitle:YZMsg(@"提交审核") forState:0];
        [upBtn setTitleColor:[UIColor whiteColor] forState:0];
        upBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        upBtn.layer.cornerRadius = 5;
        upBtn.layer.masksToBounds = YES;
        [upBtn addTarget:self action:@selector(upBtnClick) forControlEvents:UIControlEventTouchUpInside];
        [_bottomView addSubview:upBtn];
    }
    return _bottomView;
}
//商品标题
-(CommodityTitleView *)titleView{
    YBWeakSelf;
    if (!_titleView) {
        _titleView = [[CommodityTitleView alloc]initWithFrame:CGRectMake(0, self.commodityClassView.bottom+5, _window_width, 170)];
        _titleView.delegate = self;
        _titleView.heightEvent = ^(CGFloat height) {
            titleViewHeight = height;
           weakSelf.titleView.size = CGSizeMake(_window_width, height);
            [weakSelf reloadUIHeight];
        };
    }
    return _titleView;
}
//商品详情
-(CommodityDetailView *)contentView{
    YBWeakSelf;

    if (!_contentView) {
        _contentView =[[CommodityDetailView alloc]initWithFrame:CGRectMake(0, self.titleView.bottom+5, _window_width, 330)];
        _contentView.delegate = self;
        _contentView.heightEvent = ^(CGFloat height) {
            detailViewHeight = height;
           weakSelf.contentView.size = CGSizeMake(_window_width, height);
            [weakSelf reloadUIHeight];
        };

    }
    return _contentView;
}
//商品规格
-(UIView *)standardsBackView
{
    if (!_standardsBackView) {
        _standardsBackView = [[UIView alloc]init];
        _standardsBackView.frame = CGRectMake(0, self.contentView.bottom+5, _window_width, 330);
        _standardsBackView.backgroundColor = UIColor.whiteColor;
        
        UILabel*title = [[UILabel alloc]init];
        title.frame = CGRectMake(12, 10, 80, 20);
        title.font = [UIFont boldSystemFontOfSize:14];
        title.text = YZMsg(@"编辑规格");
        title.textColor = [UIColor blackColor];
        [_standardsBackView addSubview:title];

        [standarsArr addObject:self.standardsView];
        [_standardsBackView addSubview:self.standardsView];
        [_standardsBackView addSubview:self.addStdBtn];
    }
    return _standardsBackView;
}
-(StandardsView *)standardsView{
    if (!_standardsView) {
        _standardsView = [[StandardsView alloc]initWithFrame:CGRectMake(0, 40, _window_width, 240)];
        _standardsView.titleLb.text =[NSString stringWithFormat:@"%@%@",YZMsg(@"规格"),@"1"];
    }
    return _standardsView;
}

//新增规格按钮
-(UIButton *)addStdBtn{
    if (!_addStdBtn) {
        _addStdBtn = [UIButton buttonWithType:0];
        _addStdBtn.frame = CGRectMake(0, self.standardsView.bottom+5, _window_width, 40);
        [_addStdBtn setTitle:YZMsg(@"新增规格") forState:0];
        [_addStdBtn setImage:[UIImage imageNamed:@"addStard"] forState:0];
        [_addStdBtn setTitleColor:UIColor.blackColor forState:0];
        _addStdBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [_addStdBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 10, 0, 0 )];
        [_addStdBtn addTarget:self action:@selector(addStdClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _addStdBtn;
}
//邮费设置界面
-(UIView *)postageView
{
    if (!_postageView) {
        _postageView  = [[UIView alloc]initWithFrame:CGRectMake(0, self.standardsBackView.bottom+5, _window_width, 100)];
        _postageView.backgroundColor = UIColor.whiteColor;
        
        UILabel*title = [[UILabel alloc]init];
        title.frame = CGRectMake(12, 10, 180, 30);
        title.font = [UIFont boldSystemFontOfSize:14];
        title.text = YZMsg(@"运费设置");
        title.textColor = [UIColor blackColor];
        [_postageView addSubview:title];
        
        UILabel*title2 = [[UILabel alloc]init];
        title2.frame = CGRectMake(12, title.bottom+10, 180, 30);
        title2.font = [UIFont systemFontOfSize:14];
        title2.text = YZMsg(@"包邮");
        title2.textColor = UIColor.grayColor;
        [_postageView addSubview:title2];

        postageSwitch = [[UISwitch alloc]initWithFrame:CGRectMake(_window_width-90, title.bottom+10, 70, 30)];
        postageSwitch.centerY = title2.centerY;
        postageSwitch.on = YES;
        postageSwitch.onTintColor = Pink_Cor;
        [postageSwitch addTarget:self action:@selector(openPostage) forControlEvents:UIControlEventValueChanged];
        [_postageView addSubview:postageSwitch];

        postageback = [[UIView alloc]init];
        postageback.frame = CGRectMake(0, title2.bottom, _window_width, 50);
        postageback.backgroundColor = UIColor.whiteColor;
        postageback.hidden = YES;
        [_postageView addSubview:postageback];
        
        UILabel*title3 = [[UILabel alloc]init];
        title3.frame = CGRectMake(12, 10, 130, 30);
        title3.font = [UIFont boldSystemFontOfSize:14];
        title3.text = YZMsg(@"运费(元)");
        title3.textColor = UIColor.grayColor;
        [postageback addSubview:title3];
        
        postageField = [[UITextField alloc]init];
        postageField.frame = CGRectMake(title3.right+5, 10, _window_width-title3.right-25, 30);
        postageField.backgroundColor =RGB(245, 245, 245);// RGB_COLOR(@"#302D41", 1);
        postageField.textColor = [UIColor blackColor];
        postageField.font = [UIFont systemFontOfSize:14];
        
        NSMutableAttributedString*holderString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"  %@",YZMsg(@"最少1.00元")] attributes:@{NSForegroundColorAttributeName:[UIColor lightGrayColor]}];
        postageField.attributedPlaceholder = holderString;

//        postageField.placeholder = YZMsg(@"最少1.00元");
        postageField.layer.cornerRadius = 3;
        postageField.layer.masksToBounds = YES;
        postageField.returnKeyType = UIReturnKeyDone;
        postageField.keyboardType = UIKeyboardTypeNumberPad;
        postageField.delegate = self;
        [postageback addSubview:postageField];

    }
    return _postageView;
}
-(void)openPostage{
//    postageSwitch.on = !postageSwitch.on;
    if (postageSwitch.on) {
        postageHeight = 100;
        _postageView.frame =CGRectMake(0, self.standardsBackView.bottom+5, _window_width, 100);
        postageback.hidden = YES;

    }else{
        postageHeight = 150;
        _postageView.frame  = CGRectMake(0, self.standardsBackView.bottom+5, _window_width, 150);
        postageback.hidden = NO;

    }
    [self reloadUIHeight];
}
#pragma mark--佣金
-(UIView *)commissionView
{
    if (!_commissionView) {
        _commissionView = [[UIView alloc]init];
        _commissionView  = [[UIView alloc]initWithFrame:CGRectMake(0, self.postageView.bottom+5, _window_width, 100)];
        _commissionView.backgroundColor = UIColor.whiteColor;
        
        UILabel*title = [[UILabel alloc]init];
        title.frame = CGRectMake(12, 10, 280, 30);
        title.font = [UIFont boldSystemFontOfSize:14];
        title.text = YZMsg(@"分享佣金设置");
        title.textColor = [UIColor blackColor];
        [_commissionView addSubview:title];
        
        UILabel*title3 = [[UILabel alloc]init];
        title3.frame = CGRectMake(12, title.bottom+10, 130, 30);
        if (![lagType isEqual:ZH_CN]) {
            title3.frame = CGRectMake(12, title.bottom+10, 180, 30);
        }
        title3.font = [UIFont boldSystemFontOfSize:14];
        title3.text = YZMsg(@"佣金(元)");
        title3.textColor = UIColor.grayColor;
        [_commissionView addSubview:title3];
        
        commissionField = [[UITextField alloc]init];
        commissionField.frame = CGRectMake(title3.right+5, title.bottom+10, _window_width-title3.right-25, 30);
        commissionField.backgroundColor =RGB(245, 245, 245);// RGB_COLOR(@"#302D41", 1);
        commissionField.textColor = [UIColor blackColor];
        commissionField.font = [UIFont systemFontOfSize:14];
        commissionField.layer.cornerRadius = 3;
        commissionField.layer.masksToBounds = YES;
        commissionField.returnKeyType = UIReturnKeyDone;
        commissionField.delegate = self;
        [_commissionView addSubview:commissionField];

    }
    return _commissionView;
}
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (textField == commissionField) {
        if (string.length == 0) {
            return YES;
        }
        NSString *checkStr = [textField.text stringByReplacingCharactersInRange:range withString:string];
        
        NSString *regex = @"^\\-?([1-9]\\d*|0)(\\.\\d{0,2})?$";
        return [self isValid:checkStr withRegex:regex];
    }
    return YES;
}
- (BOOL) isValid:(NSString*)checkStr withRegex:(NSString*)regex {
    NSPredicate *predicte = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    return [predicte evaluateWithObject:checkStr];
}

//刷新界面
-(void)reloadUIHeight{
    self.titleView.frame = CGRectMake(0, self.commodityClassView.bottom+5, _window_width, titleViewHeight);
    self.contentView.frame = CGRectMake(0, self.titleView.bottom+5, _window_width, detailViewHeight);
    self.standardsBackView.frame = CGRectMake(0, self.contentView.bottom+5, _window_width, standardsHeight);
    self.postageView.frame = CGRectMake(0, self.standardsBackView.bottom+5, _window_width, postageHeight);
    self.commissionView.frame = CGRectMake(0, self.postageView.bottom+5, _window_width, commissionHeight);

    _backScroll.contentSize = CGSizeMake(_window_width, self.titleView.height+self.contentView.height+self.commodityClassView.height+standardsHeight+postageHeight+commissionHeight+64+statusbarHeight+60);
    NSLog(@"------------_backSscoll:%f",_backScroll.contentSize.height);
}
//商品类别
-(UIView *)commodityClassView{
    if (!_commodityClassView) {
        _commodityClassView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _window_width, 55)];
        _commodityClassView.backgroundColor = UIColor.whiteColor;
        [_backScroll addSubview:_commodityClassView];
        
        UILabel*title = [[UILabel alloc]init];
        title.frame = CGRectMake(12, 55/2-10, 180, 20);
        title.centerY = _commodityClassView.centerY;
        title.font = [UIFont boldSystemFontOfSize:14];
        title.text = YZMsg(@"商品类别");
        title.textColor = [UIColor blackColor];
        [_commodityClassView addSubview:title];
        
        UIImageView *rightImg = [[UIImageView alloc]init];
        rightImg.frame = CGRectMake(_window_width-30, 0, 16, 16);
        rightImg.centerY = _commodityClassView.centerY;
        rightImg.image = [UIImage imageNamed:@"shop_right"];
        [_commodityClassView addSubview:rightImg];
        
        _classLb = [[UILabel alloc]init];
        _classLb.frame = CGRectMake(rightImg.left-150, 0, 150, 20);
        _classLb.centerY = _commodityClassView.centerY;
        _classLb.font = [UIFont systemFontOfSize:14];
        _classLb.text = YZMsg(@"请选择");
        _classLb.textColor = [UIColor grayColor];
        _classLb.textAlignment = NSTextAlignmentRight;
        [_commodityClassView addSubview:_classLb];
        
        UITapGestureRecognizer *classTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(classClick)];
        [_commodityClassView addGestureRecognizer:classTap];
    }
    return _commodityClassView;
}
-(void)classClick{
    SelCommodityClassVC *class = [[SelCommodityClassVC alloc]init];
    class.selClassEvent = ^(NSDictionary * _Nonnull firstDic, NSDictionary * _Nonnull twoDic, NSDictionary * _Nonnull threeDic) {
        one_classidStr = minstr([firstDic valueForKey:@"gc_id"]);
        two_classidStr = minstr([twoDic valueForKey:@"gc_id"]);
        three_classidStr =minstr([threeDic valueForKey:@"gc_id"]);
        _classLb.text = minstr([threeDic valueForKey:@"gc_name"]);
    };
    [[YBBaseAppDelegate sharedAppDelegate]pushViewController:class animated:YES];
}
//添加规格
-(void)addStdClick{
    YBWeakSelf;
    StandardsView *standardsView =  [[StandardsView alloc]initWithFrame:CGRectMake(0, 40+standarsArr.count *240, _window_width, 240)];
    [_standardsBackView addSubview:standardsView];
    [standarsArr addObject:standardsView];
    standardsView.deleteBtn.hidden = NO;
    standardsView.index = (int)standarsArr.count;
    standardsView.titleLb.text = [NSString stringWithFormat:@"%@%d",YZMsg(@"规格"),standardsView.index];
    standardsView.deleteEvent = ^(NSInteger tags) {
        NSLog(@"add--------:%ld",tags);
        for(id tmpView in [weakSelf.standardsBackView subviews])
        {
            if([tmpView isKindOfClass:[StandardsView class]]){
                StandardsView *selView = (StandardsView *)tmpView;
                if (selView.index == tags) {
                    [selView removeFromSuperview];
                    [standarsArr removeObjectAtIndex:tags-1];
                }
            }
        }
        for (int i = 0; i < standarsArr.count; i ++) {
            StandardsView *imgVVVV = standarsArr[i];
            imgVVVV.y = 40+240 * i;
            imgVVVV.index = i+1;
            imgVVVV.titleLb.text = [NSString stringWithFormat:@"%@%d",YZMsg(@"规格"),imgVVVV.index];

        }

        standardsHeight = 330+240 *(standarsArr.count-1);
        self.addStdBtn.frame = CGRectMake(0, 40+standarsArr.count *240+5, _window_width, 40);
        [self reloadUIHeight];

    };
    standardsHeight = 330+240 *(standarsArr.count-1);
    self.addStdBtn.frame = CGRectMake(0, 40+standarsArr.count *240+5, _window_width, 40);
    [self reloadUIHeight];
    
}
#pragma mark------textFeildDelegate----------
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [postageField resignFirstResponder];
    return YES;
}
-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}
//获取商品标题图集
-(void)setCommodityImg:(NSMutableArray *)imgArr
{
    self.titleImgArr = [NSArray arrayWithArray:imgArr];
}
//获取商品详情图集
-(void)setCommodityDetailImg:(NSMutableArray *)imgArr
{
    self.detailImgArr = [NSArray arrayWithArray:imgArr];
}
#pragma mark------上传信息----------
-(void)upBtnClick{
    [self.standardsImgArr removeAllObjects];
    if ([_classLb.text isEqual:YZMsg(@"请选择")]) {
        [MBProgressHUD showError:YZMsg(@"请选择商品类别")];
        return;
    }
    if (self.titleView.titleText.text.length < 1) {
        [MBProgressHUD showError:YZMsg(@"请填写商品标题")];
        return;
    }
    if (self.titleImgArr.count < 1){
        [MBProgressHUD showError:YZMsg(@"请先上传图片信息")];
        return;
    }
    if (self.contentView.contentText.text.length < 1) {
        [MBProgressHUD showError:YZMsg(@"请填写商品详情")];
        return;
    }
    for (int i = 0; i < standarsArr.count; i ++) {
        StandardsView *imgVVVV = standarsArr[i];
        NSLog(@"adddddddd=====:%@",imgVVVV.imageArray);
        if (imgVVVV.nameField.text.length < 1) {
            [MBProgressHUD showError:YZMsg(@"请填写规格名称")];
            return;
        }else if(imgVVVV.countField.text.length < 1){
            [MBProgressHUD showError:YZMsg(@"请填写库存")];
            return;
        }else if(imgVVVV.priceField.text.length < 1){
            [MBProgressHUD showError:YZMsg(@"请填写单价")];
            return;
        }
        
        if (imgVVVV.imageArray.count < 1) {
            [MBProgressHUD showError:YZMsg(@"请先上传规格图片")];
            return;
        }
    }
    [MBProgressHUD showMessage:@""];
    YBWeakSelf;
    [[YBStorageObj storageManeger]getCOSType:^(int code) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (code == 0) {
                [weakSelf uploadAllImageAndVideo];
            }
        });
    }];

//    [YBToolClass postNetworkWithUrl:@"Video.GetQiniuToken" andParameter:nil success:^(int code, id  _Nonnull info, NSString * _Nonnull msg) {
//        if (code == 0) {
//            NSDictionary *dic = [info firstObject];
//            if (self.titleView.videoPath.length > 0) {
//                NSLog(@"有视频-------");
//                if([self.titleView.videoPath containsString:[common qiniu_domain]]){
//                    videoCorverStr = self.commodityModel.video_thumb;
//                    videoHerfStr = self.commodityModel.video_url;
//                    [self uploadImage:minstr([dic valueForKey:@"token"])];
//                }else{
//                    [self uploadVideoWithToken:minstr([dic valueForKey:@"token"])];
//                }
//            }else{
//                [self uploadImage:minstr([dic valueForKey:@"token"])];
//            }
//        }else{
//            [MBProgressHUD hideHUD];
//            [MBProgressHUD showError:msg];
//        }
//    } fail:^{
//        [MBProgressHUD hideHUD];
//    }];
}
//上传所有图片和视频
-(void)uploadAllImageAndVideo{
    YBWeakSelf;
    dispatch_group_t group = dispatch_group_create();
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);

    //********************上传商品标题内容开始*****************************//
    //如果有视频
    if (self.titleView.newvideoPath.length > 0  || self.titleView.videoPath.length > 0) {
        //如果有本地视频使用本地视频
        if (self.titleView.newvideoPath.length > 0) {
            dispatch_group_async(group, queue, ^{
                NSString *videoName = [PublicObj getNameBaseCurrentTime:@"_seller_action_video.mp4"];
                
                [[YBStorageObj storageManeger]yb_storageVideoOrVoice:self.titleView.videoPath andName:videoName progress:^(CGFloat percent) {
                    
                } complete:^(int code, NSString *key) {
                    if (code != 0) {
                        dispatch_async(dispatch_get_main_queue(), ^{
                            [MBProgressHUD hideHUD];
                            [MBProgressHUD showPop:YZMsg(@"上传失败")];
                        });
                        return;
                    }

                    videoHerfStr = key;
                    dispatch_semaphore_signal(semaphore);
                }];

                dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
            });

        }else{
            //这是是服务端返回的视频链接
            videoCorverStr = self.commodityModel.video_thumb;
            videoHerfStr = self.commodityModel.video_url;
        }
    }
    if (self.titleImgArr.count > 0) {
        _upTitleImgArr = [NSMutableArray array];
        thumbs = @"";
        for (int i = 0; i < self.titleImgArr.count ; i ++) {
            if ([self.titleImgArr[i] isKindOfClass:[UIImage class]]) {
                UIImage *image =self.titleImgArr[i];
                NSData *imageData = UIImagePNGRepresentation(image);
                if (!imageData) {
                    [MBProgressHUD hideHUD];
                    [MBProgressHUD showError:YZMsg(@"图片错误")];
                    return;
                }
                dispatch_group_async(group, queue, ^{
                    NSString *imageName = [PublicObj getNameBaseCurrentTime:[NSString stringWithFormat:@"_commodity_title_image%d_cover.png", i]];
                    [[YBStorageObj storageManeger]yb_storageImg:image andName:imageName progress:^(CGFloat percent) {
                        
                    }complete:^(int code, NSString *key) {
                        if (code != 0) {
                            dispatch_async(dispatch_get_main_queue(), ^{
                                [MBProgressHUD hideHUD];
                                [MBProgressHUD showPop:YZMsg(@"上传失败")];
                            });
                            return;
                        }
                        [_upTitleImgArr addObject:key];
                        dispatch_semaphore_signal(semaphore);
                    }];
                    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
                });

            }else{
                NSString *imgthumb =self.titleImgArr[i];
                NSArray *imgArr = [imgthumb componentsSeparatedByString:@"/"];
                imgthumb = [imgArr lastObject];
                [_upTitleImgArr addObject:imgthumb];
            }
        }
    };
    
    //********************上传商品标题内容结束*****************************//

    //********************上传商品详情内容开始*****************************//
    if (self.detailImgArr.count > 0) {

        _upDetailImgArr = [NSMutableArray array];
        pictures = @"";
        for (int i = 0; i < self.detailImgArr.count ; i ++) {
            if ([self.detailImgArr[i] isKindOfClass:[UIImage class]]) {

                UIImage *image =self.detailImgArr[i];
                NSData *imageData = UIImagePNGRepresentation(image);
                if (!imageData) {
                    [MBProgressHUD hideHUD];
                    [MBProgressHUD showError:YZMsg(@"图片错误")];
                    return;
                }
                dispatch_group_async(group, queue, ^{
                    NSString *imageName = [PublicObj getNameBaseCurrentTime:[NSString stringWithFormat:@"_commodity_detail_image%d_cover.png", i]];
                    [[YBStorageObj storageManeger]yb_storageImg:image andName:imageName progress:^(CGFloat percent) {
                        
                    }complete:^(int code, NSString *key) {
                        if (code != 0) {
                            dispatch_async(dispatch_get_main_queue(), ^{
                                [MBProgressHUD hideHUD];
                                [MBProgressHUD showPop:YZMsg(@"上传失败")];
                            });

                            return;
                        }

                        [_upDetailImgArr addObject:key];
                        dispatch_semaphore_signal(semaphore);
                    }];
                    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
                });

            }else{
                NSString *imgthumb =self.detailImgArr[i];
                NSArray *imgArr = [imgthumb componentsSeparatedByString:@"/"];
                imgthumb = [imgArr lastObject];
                [_upDetailImgArr addObject:imgthumb];

            }
        }
    }else{
        picturesBool = YES;
        pictures = @"";

    }
    
    //********************上传商品详情内容结束*****************************//
    dispatch_group_notify(group, queue, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            NSMutableArray * sortTitleArr = [self compareArrWithArray:_upTitleImgArr];
            for (NSString *str in sortTitleArr) {
                if (thumbs.length == 0) {
                    thumbs = str;
                }else{
                    thumbs = [NSString stringWithFormat:@"%@,%@",thumbs,str];
                }
            }
            NSLog(@"-------标题图片合并完成------:%@",thumbs);
            thumbsBool = YES;

            NSMutableArray * sortDetailArr = [self compareArrWithArray:_upDetailImgArr];
             for (NSString *str in sortDetailArr) {
                 if (pictures.length == 0) {
                     pictures = str;
                 }else{
                     pictures = [NSString stringWithFormat:@"%@,%@",pictures,str];
                 }
             }
             picturesBool = YES;

            if (thumbsBool && picturesBool) {
                [weakSelf uploadStandImg];
            }

        });
        NSLog(@"任务完成执行");
    });

}
//上传商品规格图片开始
-(void)uploadStandImg{
    YBWeakSelf;
    dispatch_group_t group = dispatch_group_create();
    dispatch_queue_t queue = dispatch_get_global_queue(0, 0);
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);

    for (int i = 0; i < standarsArr.count; i ++) {
        StandardsView *imgVVVV = standarsArr[i];
        if ([imgVVVV.imageArray[0] isKindOfClass:[UIImage class]]) {
            UIImage *image =imgVVVV.imageArray[0];
            NSData *imageData = UIImagePNGRepresentation(image);
            if (!imageData) {
                [MBProgressHUD hideHUD];
                [MBProgressHUD showError:YZMsg(@"图片错误")];
                return;
            }
            dispatch_group_async(group, queue, ^{
                NSString *imageName = [PublicObj getNameBaseCurrentTime:[NSString stringWithFormat:@"_commodity_standard_image%d_cover.png", i]];
                [[YBStorageObj storageManeger]yb_storageImg:image andName:imageName progress:^(CGFloat percent) {
                    
                }complete:^(int code, NSString *key) {
                    if (code != 0) {
                         dispatch_async(dispatch_get_main_queue(), ^{
                             [MBProgressHUD hideHUD];
                             [MBProgressHUD showPop:YZMsg(@"上传失败")];
                         });
                         return;
                     }

                    [self.standardsImgArr addObject:key];
                    if (self.standardsImgArr.count == standarsArr.count) {
                        standardsBool = YES;
                    }

                    dispatch_semaphore_signal(semaphore);
                }];
                dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
            });
        }else{
            NSString *imgthumb = [imgVVVV.imageArray[0] stringByReplacingOccurrencesOfString:[common qiniu_domain] withString:@""];
            [self.standardsImgArr addObject:imgthumb];
            if (self.standardsImgArr.count == standarsArr.count) {
                standardsBool = YES;
            }

        }
    }
    dispatch_group_notify(group, queue, ^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (standardsBool == YES) {
                [weakSelf submitService];
            }
        });
        NSLog(@"任务完成执行");
    });
}
-(NSMutableArray *)compareArrWithArray:(NSArray *)arr{
    //图片排序
     NSMutableDictionary *dict = [NSMutableDictionary dictionary];

    //这块取出数组中的数字，  请根据自己数组而定
    for (int i = 0; i < arr.count; i++) {
        NSArray *array = [arr[i] componentsSeparatedByString:@"_image"];
        NSString *str_t = [array lastObject];
        
        NSArray *array_t =[str_t componentsSeparatedByString:@"_cover"];
        NSString *str = [array_t firstObject];

        [dict setValue:arr[i] forKey:str];
    }

    NSArray *arrKey = [dict allKeys];
    //将key排序
    NSArray *sortedArray = [arrKey sortedArrayUsingComparator:^NSComparisonResult(id obj1,id obj2) {
        return[obj1 compare:obj2 options:NSNumericSearch];//正序
    }];
    
    NSMutableArray *orderValueArray=[NSMutableArray array];
    
    //根据key的顺序提取相应value
    for (NSString *key in sortedArray) {
        [orderValueArray addObject:[dict objectForKey:key]];
    }
    return orderValueArray;
}
-(void)submitService{

    NSString *postage;
    if (!postageSwitch.on) {
        postage = postageField.text;
        if (postage.length < 1) {
            [MBProgressHUD hideHUD];

            [MBProgressHUD showError:YZMsg(@"请输入运费")];
            return;
        }
    }else{
        postage = @"0";
    }
    NSString *share_income;
    if (commissionField.text.length < 1) {
        share_income = @"0";
    }else{
        share_income = commissionField.text;
    }

    NSMutableArray *specsArr = [NSMutableArray array];
    for (int i = 0; i < standarsArr.count; i ++) {
        StandardsView *imgVVVV = standarsArr[i];
        NSString *standard_image = [NSString stringWithFormat:@"_standard_image%d",i];
        NSString *selImageStr;
        for (NSString *picStr in self.standardsImgArr) {
            if ([picStr containsString:standard_image]) {
                selImageStr = picStr;
            }
        }

        NSString *spec_id = [NSString stringWithFormat:@"%d",i+1];
        NSString *spec_name = imgVVVV.nameField.text;
        NSString *spec_num = imgVVVV.countField.text;
        NSString *price = imgVVVV.priceField.text;
        NSString *thumb = selImageStr;
        
        NSMutableDictionary *specDic = [NSMutableDictionary dictionary];
        [specDic setValue:spec_id forKey:@"spec_id"];
        [specDic setValue:spec_name forKey:@"spec_name"];
        [specDic setValue:spec_num forKey:@"spec_num"];
        [specDic setValue:price forKey:@"price"];
        [specDic setValue:thumb forKey:@"thumb"];
        [specsArr addObject:specDic];
    }
    NSString *specsStr =  [self gs_jsonStringCompactFormatForNSArray:specsArr];
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setValue:[Config getOwnID] forKey:@"uid"];
    [dic setValue:[Config getOwnToken] forKey:@"token"];
    [dic setValue:one_classidStr forKey:@"one_classid"];
    [dic setValue:two_classidStr forKey:@"two_classid"];
    [dic setValue:three_classidStr forKey:@"three_classid"];
    [dic setValue:self.titleView.titleText.text forKey:@"name"];
    [dic setValue:videoHerfStr forKey:@"video_url"];
    [dic setValue:videoCorverStr forKey:@"video_thumb"];
    [dic setValue:thumbs forKey:@"thumbs"];
    [dic setValue:self.contentView.contentText.text forKey:@"content"];
    [dic setValue:pictures forKey:@"pictures"];
    [dic setValue:specsStr forKey:@"specs"];
    [dic setValue:postage forKey:@"postage"];
    [dic setValue:share_income forKey:@"share_income"];

    NSString *url;
    if ([self.fromWhere isEqual:@"seller"]) {
//        url = [purl stringByAppendingFormat:@"?service=Seller.upgoods"];
        url = @"Seller.upgoods";
        [dic setValue:self.commodityModel.goodsid forKey:@"goodsid"];

    }else{
        url = @"Seller.setGoods";

    }
    
    [WYNetworking postWithUrl:url Dic:dic Suc:^(int code, id info, NSString *msg) {
        [MBProgressHUD hideHUD];
        if (code ==0) {
            [MBProgressHUD showError: msg];
            [[YBBaseAppDelegate sharedAppDelegate]popViewController:YES];
        }else{
            [MBProgressHUD showError:msg];
        }

        } Fail:^(id fail) {
            [MBProgressHUD hideHUD];

     }];

}

- (NSString *)gs_jsonStringCompactFormatForNSArray:(NSArray *)arrJson {
    if (![arrJson isKindOfClass:[NSArray class]] || ![NSJSONSerialization isValidJSONObject:arrJson]) {
        return nil;
    }
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:arrJson options:0 error:nil];
    NSString *strJson = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return strJson;
}
#pragma mark-------商家编辑商品赋值-----------------
-(void)reloadUIData{
    _classLb.text = self.commodityModel.three_class_name;
    one_classidStr =self.commodityModel.one_classid;
    two_classidStr = self.commodityModel.two_classid;
    three_classidStr =self.commodityModel.three_classid;

    self.titleView.titleText.text =self.commodityModel.name;
    [self.titleView setDetaiModelData:self.commodityModel fromWhere:@"seller"];
    
    commissionField.text = minstr([self.commodityModel.goods_info valueForKey:@"share_income"]);

    self.contentView.contentText.text = self.commodityModel.content;
    [self.contentView setDetaiModelData:self.commodityModel fromWhere:@"seller"];

    if (self.commodityModel.specs_format.count > 0) {
        for (int i = 1; i < self.commodityModel.specs_format.count; i++) {
            [self addStdClick];
        }
        for (int i = 0; i < standarsArr.count; i ++) {
            StandardsView *imgVVVV = standarsArr[i];
            imgVVVV.nameField.text = minstr([self.commodityModel.specs_format[i] valueForKey:@"spec_name"]);
            imgVVVV.countField.text = minstr([self.commodityModel.specs_format[i] valueForKey:@"spec_num"]);
            imgVVVV.priceField.text = minstr([self.commodityModel.specs_format[i] valueForKey:@"price"]);
            
            NSString *imgurl =minstr([self.commodityModel.specs_format[i] valueForKey:@"thumb"]);
            [imgVVVV.imgeBtn sd_setBackgroundImageWithURL:[NSURL URLWithString:imgurl] forState:0];
            [imgVVVV.imgeBtn setImage:nil forState:0];
            [imgVVVV.imgeBtn setTitle:nil forState:0];
            imgVVVV.delBtn.hidden = NO;
            [imgVVVV.imageArray removeAllObjects];
            [imgVVVV.imageArray addObject:imgurl];

        }
    }
    if ([self.commodityModel.postage floatValue] > 0) {
        postageSwitch.on = YES;
        [self openPostage];
        postageField.text = self.commodityModel.postage;
    }else{
        postageSwitch.on = YES;

    }
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
//    NSLog(@"jjjjjjjj:%f",scrollView.contentOffset.y);
    currentScrollY =scrollView.contentOffset.y;
}
#pragma mark -- 获取键盘高度
- (void)keyboardWillShow:(NSNotification *)aNotification
{
    if (postageField.isFirstResponder||commissionField.isFirstResponder) {
            NSDictionary *userInfo = [aNotification userInfo];
        NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
        CGRect keyboardRect = [aValue CGRectValue];
        CGFloat height = keyboardRect.origin.y;
        CGFloat heightw = keyboardRect.size.height;
        int newHeight = _window_height - height -44;
        [UIView animateWithDuration:0.3 animations:^{
            [_backScroll setContentOffset:CGPointMake(0, currentScrollY+heightw)];
        }];
    }
    //获取键盘的高度
}
- (void)keyboardWillHide:(NSNotification *)aNotification
{

    if (postageField.resignFirstResponder) {
        NSDictionary *userInfo = [aNotification userInfo];
        NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
        CGRect keyboardRect = [aValue CGRectValue];
        CGFloat height = keyboardRect.origin.y;
        CGFloat heightw = keyboardRect.size.height;

        [UIView animateWithDuration:0.1 animations:^{
            [UIView animateWithDuration:0.3 animations:^{
                [_backScroll setContentOffset:CGPointMake(0, currentScrollY-heightw)];
            }];
        }];

//        [UIView animateWithDuration:0.1 animations:^{
//            [UIView animateWithDuration:0.3 animations:^{
//                [_backScroll setContentOffset:CGPointMake(0, 520)];
//            }];
//        }];

    }
//    else{
//        [UIView animateWithDuration:0.1 animations:^{
//            [UIView animateWithDuration:0.3 animations:^{
//                [_backScroll setContentOffset:CGPointMake(0, 0)];
//            }];
//        }];
//
//    }

}

@end
